<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-show="listQuery.showReviewer"
        v-model="orderDate"
        type="date"
        placeholder="选择日期"
        :picker-options="pickerOptions"
      />
      <el-input
        v-model="listQuery.name"
        placeholder="名称"
        style="width: 200px;"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button>
      <el-button
        v-show="!isSetting"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleSetting"
      >
        点餐初始化设置
      </el-button>
      <el-checkbox v-model="listQuery.showReviewer" class="filter-item" style="margin-left:15px;" @change="getList">
        历史记录
      </el-checkbox>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="点餐人" align="center">
        <template slot-scope="{ row }">
          {{ row.username }}
        </template>
      </el-table-column>
      <el-table-column label="饮品" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.drinkName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年季度" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.yearQuarter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{ row }">
          {{ row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template slot-scope="{ row }">
          {{ row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="!listQuery.showReviewer"
        label="操作"
        align="center"
        width="250"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!--    编辑模拟框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="点餐人">
          <el-input
            v-model="temp.username"
            type="text"
            placeholder="点餐人"
          />
        </el-form-item>

        <el-form-item label="饮品">
          <!-- <el-input v-model="temp.drink" type="text" placeholder="饮品" /> -->
          <el-select
            v-model="temp.drinkName"
            filterable
            remote
            reserve-keyword
            placeholder="饮品"
            :remote-method="remoteMethod"
            :loading="loading"
            @change="currentSel"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="价格">
          <el-input v-model="temp.price" type="text" placeholder="饮品价格" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>

    <!--  新增模拟框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogAddFormVisible">
      <el-form
        ref="dataAddForm"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="点餐人">
          <el-input
            v-model="temp.username"
            type="text"
            placeholder="点餐人"
          />
        </el-form-item>

        <el-form-item label="饮品">
          <!-- <el-input v-model="temp.drink" type="text" placeholder="饮品" /> -->
          <el-select
            v-model="temp.drinkName"
            filterable
            remote
            reserve-keyword
            placeholder="饮品"
            :remote-method="remoteMethod"
            :loading="loading"
            @change="currentSel"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="价格">
          <el-input v-model="temp.price" type="text" placeholder="饮品价格" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false"> 关闭 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 初始化设置 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogSettingFormVisible"
    >
      <el-form
        ref="dataSettingForm"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-select
          v-model="value"
          filterable
          remote
          reserve-keyword
          placeholder="默认饮品"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSettingFormVisible = false"> 关闭 </el-button>
        <el-button type="primary" @click="setting()"> 提交 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteUserRecord,
  saveOrUpdateOrder,
  selectUserRecordByLimit,
  judgeOrder,
  getDrinkList,
  setOrder
} from '@/api/userrecord'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  data() {
    return {
      yearAndQuarter: '',
      options: [],
      value: [],
      drinkList: [],
      loading: false,
      states: [
        'Alabama',
        'Alaska',
        'Arizona',
        'Arkansas',
        'California',
        'Colorado',
        'Connecticut',
        'Delaware',
        'Florida',
        'Georgia',
        'Hawaii',
        'Idaho',
        'Illinois',
        'Indiana',
        'Iowa',
        'Kansas',
        'Kentucky',
        'Louisiana',
        'Maine',
        'Maryland',
        'Massachusetts',
        'Michigan',
        'Minnesota',
        'Mississippi',
        'Missouri',
        'Montana',
        'Nebraska',
        'Nevada',
        'New Hampshire',
        'New Jersey',
        'New Mexico',
        'New York',
        'North Carolina',
        'North Dakota',
        'Ohio',
        'Oklahoma',
        'Oregon',
        'Pennsylvania',
        'Rhode Island',
        'South Carolina',
        'South Dakota',
        'Tennessee',
        'Texas',
        'Utah',
        'Vermont',
        'Virginia',
        'Washington',
        'West Virginia',
        'Wisconsin',
        'Wyoming'
      ],
      isSetting: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      value1: '',
      orderDate: parseTime(new Date(), '{y}-{m}-{d}'),
      today: parseTime(new Date(), '{y}-{m}-{d}'),
      total: 0,
      list: [
        {
          id: '',
          username: '',
          drinkName: '',
          price: '',
          createTime: '',
          updateTime: ''
        }
      ],
      listQuery: {
        page: 1,
        limit: 10,
        name: '',
        orderDate: parseTime(new Date(), '{y}-{m}-{d}'),
        showReviewer: false
      },
      temp: {
        id: '',
        name: '',
        username: '',
        price: '',
        drinkId: '',
        userId: '',
        drinkName: '',
        yearQuarter: ''
      },
      listLoading: true,
      downloadLoading: false,
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      dialogSettingFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        init: '初始化'
      }
    }
  },
  mounted() {
    this.drinkList = this.states.map((item) => {
      return { value: `value:${item}`, label: `label:${item}` }
    })
  },
  created() {
    this.fetchData()
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    // 新增
    createData() {
      this.$refs['dataAddForm'].validate((valid) => {
        if (valid) {
          saveOrUpdateOrder(this.temp).then((res) => {
            // eslint-disable-next-line eqeqeq
            if (res.data.code != 200) {
              this.$notify({
                title: '警告',
                message: res.data.msg,
                type: 'warning',
                duration: 1000
              })
              return;
            }
            this.getList()
            this.dialogAddFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000
            })
          })
        }
      })
    },
    currentSel(selVal) {
      // alert(selVal)
      this.temp.drinkId = selVal.value
      this.temp.drinkName = selVal.label
    },
    // 更新数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          saveOrUpdateOrder(tempData).then((res) => {
            // eslint-disable-next-line eqeqeq
            if (res.data.code != 200) {
              this.$notify({
                title: '警告',
                message: res.data.msg,
                type: 'warning',
                duration: 1000
              })
              return;
            }
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000
            })
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        username: '',
        price: '',
        drinkId: '',
        userId: '',
        drinkName: '',
        yearQuarter: this.yearAndQuarter
      }
    },
    handleCreate() {
      this.initCurrQuarter()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogAddFormVisible = true
      this.getDrinkList()
      this.$nextTick(() => {
        this.$refs['dataAddForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      // 获取所有的任务id和任务名称
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getDrinkList()
      this.value = this.temp
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSetting() {
      this.resetTemp()
      this.dialogStatus = 'init'
      this.dialogSettingFormVisible = true
      this.getDrinkList()
      this.$nextTick(() => {
        this.$refs['dataSettingForm'].clearValidate()
      })
    },
    // 获取当前年和季度 例如 2021-3
    initCurrQuarter() {
      const nowDate = new Date()
      const y = nowDate.getFullYear()
      const currMonth = nowDate.getMonth() + 1
      const currQuarter = Math.floor(
        currMonth % 3 === 0 ? currMonth / 3 : currMonth / 3 + 1
      )
      this.yearAndQuarter = y + '-' + currQuarter
    },
    setting() {
      this.$refs['dataSettingForm'].validate((valid) => {
        if (valid) {
          this.initCurrQuarter()
          // eslint-disable-next-line no-unused-vars
          const tempData = Object.assign({}, this.temp)
          setOrder(this.yearAndQuarter, this.value).then(() => {
            this.dialogSettingFormVisible = false
            this.getList()
            this.isInit()
            this.$notify({
              title: '成功',
              message: '设置成功',
              type: 'success',
              duration: 1000
            })
          })
        }
      })
    },
    // 删除
    handleDelete(row, index) {
      // 删除数据库
      deleteUserRecord(row.id).then(() => {})
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 1000
      })
      this.list.splice(index, 1)
    },
    fetchData() {
      this.getList()
    },
    isInit() {
      // eslint-disable-next-line eqeqeq
      if (this.listQuery.orderDate == this.today) {
        judgeOrder(this.listQuery.orderDate).then((response) => {
          this.isSetting = response.data.data
        })
      } else {
        this.isSetting = true
      }
    },
    getDrinkList() {
      getDrinkList().then((response) => {
        this.options = response.data.data.map((item) => {
          return { value: `${item.id}`, label: `${item.name}` }
        })
      })
    },
    getList() {
      this.isInit()

      selectUserRecordByLimit(
        this.listQuery.page,
        this.listQuery.limit,
        this.listQuery.name,
        this.listQuery.orderDate,
        this.listQuery.showReviewer
      ).then((response) => {
        this.list = response.data.data.data
        this.total = response.data.data.pageTotal
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.orderDate = parseTime(this.orderDate, '{y}-{m}-{d}')
      this.listQuery.page = 1
      this.listLoading = true
      // eslint-disable-next-line eqeqeq
      // if (this.listQuery.orderDate != parseTime(new Date(), '{y}-{m}-{d}')) {
      //   this.isShow = false
      // } else {
      //   this.isShow = true
      // }
      this.getList()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['名字', '饮品', '创建时间', '更新时间']
        const filterVal = ['username', 'drinkName', 'createTime', 'updateTime']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '点餐记录表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
<!--<style lang="scss" scoped>-->
<!--.filter-container{-->
<!--  text-align: center;-->
<!--}-->
<!--</style>-->
